<template>
    <div>

        <Tabs
            :value="currentTab"
            type="card"
            :animated="false"
            @on-click="changePage"
            @on-tab-remove="removeTab">
            <TabPane label="开票信息" name="contract-list">
            <div class="merchant-wrap">
                <div class="yd-header margin-top-8">
                    <span>开票信息</span>
                    <span>
                        <Button type="primary" style="margin-right:10px" @click="contractShow" v-if="roleId == 100">新增开票</Button>
                    </span>
                </div>
                <Row :gutter="16" class='flex-style' style='padding: 15px 0;'>
                    <Col span='7'>
                        签约主体
                        <Select
                            v-model="filterData.clientMainId"
                            filterable
                            remote
                            clearable
                            class="flex-items"
                            placeholder="签约主体"
                            :remote-method="remoteMethodMangersign"
                            :loading="mangersignLoading">
                            <Option v-for="(item, key, index) in mangersign" :value="item.value" :key="index">{{ item.label }}</Option>
                        </Select>
                    </Col>
                    <Col span='7'>
                        开票状态
                        <Select
                            v-model="filterData.status"
                            clearable
                            placeholder='不限'
                            class='flex-items'>
                            <Option :value="0">审核中</Option>
                            <Option :value="2">已通过</Option>
                            <Option :value="3">已驳回</Option>
                            <Option :value="4">已取消</Option>
                        </Select>
                    </Col>
                    <Col span='10'>
                        创建日期
                        <DatePicker
                        class="flex-items"
                        placeholder="开始时间"
                        type="date"
                         @on-change="createStartTimeChange"
                        v-model="filterData.createStartTime"></DatePicker>
                        &nbsp;-&nbsp;
                        <DatePicker
                        class="flex-items"
                        placeholder="结束时间"
                        type="date"
                        @on-change="createEndTimeChange"
                        v-model="filterData.createEndTime"></DatePicker>
                    </Col>
                </Row>
                <Row :gutter="16" class='flex-style' style='padding-bottom: 15px;'>
                    <Col span='7'>
                        搜索关键字
                        <Input v-model="filterData.keyword" class='flex-items' placeholder="开票编号"/>
                        <Button type="primary" @click="handleSearch" style='margin-left: 5px;'>搜索</Button>
                    </Col>
                </Row>
                <Table stripe border :columns="columns" :data="tableData" :loading="loading"></Table>

                <p class="text-center margin-top-20">
                    <!--分页-->
                    <Page :total="total"
                    :page-size="size"
                    :current.sync="currentPage"
                    show-elevator
                    @on-change="getClientList"
                    show-total style="text-align:center"></Page>
                    <!--分页end-->
                </p>
            </div>
            </TabPane>
            <TabPane label="新增开票" name="contract-add" v-if="contractAddShow">
                <invoiceDetail :billId="billId"></invoiceDetail>
            </TabPane>
            <TabPane
            v-for="(tab,index) in tabs"
            :name="''+ tab.id"
            :key="tab.id + index"
            :label="tab.name" closable>
                <!-- <contractDetail ></contractDetail> -->
                <invoiceViewDetail :id="currentId" v-if="tab.name.indexOf('查看')!==-1"></invoiceViewDetail>
                <invoiceDetail v-else :id="currentId"></invoiceDetail>
            </TabPane>
        </Tabs>
        <!-- 同意不同意model -->
        <Modal
            :title="invoiceTitle"
            v-model="invoiceShow"
            >
            <Form ref="invoiceForm" :model="invoiceForm" :rules="rules">
                <Row>
                    <FormItem
                    prop="reject"
                    label="备注"
                    :required="!aa"
                    >
                        <i-input type="textarea" v-model="invoiceForm.reject" ></i-input>
                    </FormItem>
                </Row>
            </Form >
            <Row slot="footer">
                <Button type="text" @click="handleInvoiceCancel">取消</Button>
                <Button type="primary"  @click="handleAudit('invoiceForm')">确定</Button>
            </Row>
        </Modal>
    </div>
</template>

<script>
    import util from '@/libs/util'
import dataCenter from '@/libs/dataCenter'
import { http, api } from '@/libs/http'
import invoiceDetail from './invoice-detail'
import invoiceViewDetail from './invoice-detail-view'

import moment from 'moment'
export default {
      name: 'inner-account',
      components: {
        invoiceViewDetail,
        invoiceDetail
      },
      computed: {

        aa: function () {
          return this.invoiceTitle === '同意开票申请'
        }
      },
      data () {
        const reject = (rule, value, callback) => {
          if (this.invoiceTitle === '同意开票申请') {
            return callback()
          } else if (!value) {
            return callback(new Error('备注不能为空'))
          } else {
            return callback()
          }
        }
        return {
          roleId: null,
          billId: null,
          client: {}, // 商户
          invoiceTitle: null, // modaltitle
          invoiceForm: {}, // modalform
          invoiceShow: false, // modal
          currentId: null, // id
          contractAddShow: false, // 新建合同显示
          mangersignLoading: false, // 客户签约主体
          filterData: {}, // 搜索列表
          currentTab: 'contract-list', // 当前标签
          tabs: [], // 标签列表
          mangersign: [], // 商户
          clients: [], // 商户
          clientLoading: false, // 签约商户
          total: 0,
          size: 20,
          currentPage: 1,
          columns: [
            {
              minWidth: 180,
              align: 'center',
              title: '开票账号',
              key: 'seqno'

            },
            {
              minWidth: 160,
              align: 'center',
              title: '商户',
              key: 'clientName'
            },
            {
              minWidth: 100,
              align: 'center',
              title: '账单数',
              key: 'billNum'
            },
            {
              minWidth: 100,
              align: 'center',
              title: '商户签约主体',
              key: 'clientMainName'
            },
            {
              minWidth: 100,
              align: 'center',
              title: '纳税人识别号',
              key: 'taxpayerNum'
            },
            {
              minWidth: 100,
              align: 'center',
              title: '开票金额',
              key: 'amount'
            },
            {
              minWidth: 100,
              align: 'center',
              title: '开票状态',
              key: 'statusName',
              render: (h, params) => {
                let status = ''
                if (params.row.statusName === '待经营审核') {
                  status = '审核中'
                } else if (params.row.statusName === '待财务审核') {
                  status = '审核中'
                } else {
                  status = params.row.statusName
                }
                // params.row.statusName == '待经营审核' || '待财务审核' ? '审核中' : params.row.statusName;
                return [
                  <span>{status}</span>
                ]
              }
            },
            {
              minWidth: 160,
              align: 'center',
              title: '创建时间',
              key: 'createTime'
            },
            {
              minWidth: 260,
              align: 'center',
              title: '操作',
              fixed: 'right',
              render: (h, params) => {
                const commonProperty = {
                  style: { 'margin-right': '4px' },
                  props: { size: 'small' }
                }
                let btn = []
                if (params.row.status !== 0) {
                  if (this.roleId === 100) {
                    btn = [
                      <i-button {...commonProperty} onClick={() => this.handleCheck(params.row)}>查看</i-button>
                    ]
                  } else {
                    btn = []
                  }
                } else {
                  if (this.roleId === 100) {
                    btn = [
                      <i-button {...commonProperty} onClick={() => this.handleCheck(params.row)}>查看</i-button>,
                      <i-button {...commonProperty} onClick={() => this.handleEdit(params.row)}>编辑</i-button>
                    ]
                  } else {
                    btn = []
                  }
                }
                return btn
              }
            }
          ], // 列表结构
          loading: false,
          tableData: [

          ], // 列表数据
          search: {
            id: '',
            area: '',
            role: '',
            keyword: '',
            business_man: ''
          },
          modal: {
            show: false,
            title: '添加',
            currentMerchant: null
          }, // modal显示
          selectedTags: [],
          clientTags: [],
          tagsMap: {},
          rules: {
            reject: [
              { validator: reject, message: '备注不能为空', trigger: 'blur' }
            ]
          }
        }
      },
      created () {
        if (sessionStorage.getItem('billId')) {
          this.contractShow()
          this.billId = sessionStorage.getItem('billId')
          sessionStorage.removeItem('billId')
        }// 账单过来开票
        this.getUserInfo()
        this.getMangersign()// 签约主体
      },
      methods: {
        contractShow () {
          this.contractAddShow = true
          this.currentTab = 'contract-add'
        }, // 新建合同显示
        changePage (name) {
          this.currentTab = name
        }, // 标签更改
        bill_begin_change () {

        }, // 创建开始时间
        bill_end_change () {

        }, // 创建结束时间
        handleSearch () {
          this.getClientList(1)
        }, // 搜索
        getClientList (page) {
          if (page === 1) {
            this.currentPage = 1
          }
          this.filterData.clientId = this.client.clientId
          this.filterData.limit = this.size
          this.filterData.offset = this.size * (page - 1) || 0
          this.loading = true
          http.request(this, api.invoice_list, null, this.filterData, (res, err) => {
            this.loading = false
            if (res) {
              this.tableData = res.rows
              this.total = res.count
            }
          })
        }, // 分页
        handleRefresh () {
          this.getClientList(1)
          this.modal.show = false
        }, // 刷新
        handleDelete (item) {
          this.$Modal.confirm({
            title: '确定删除账号?',
            content: `<p><b style="color:red">${util.escapeHtml(item.name)}</b> 将会被删除</p>`,
            onOk: () => {
              this.confirmDelete(item.id)
            },
            onCancel: () => {
              this.$Message.info('取消删除')
            }
          })
        }, // 删除
        confirmDelete (id) {
          http.request(this, api.clients_delete, [id], null, (res, err) => {
            if (res) {
              this.getClientList(1)
              this.$Message.info('删除成功')
              dataCenter.updateClients()
            }
          })
        }, // 确认删除
        handleEdit (merchant) {
          console.log(merchant)
          // 打开新标签显示详情
          let id = '' + merchant.id
          let name = '' + merchant.seqno + '(编辑)'
          this.toContractDetail(id, name)
        }, // 编辑
        handleCheck (merchant) {
          // 打开新标签显示详情
          let id = '' + merchant.id
          let name = '' + merchant.seqno + '(查看)'
          this.toContractDetail(id, name)
        }, // 查看
        handleSure (row) {
          this.invoiceForm = {}
          this.invoiceShow = true
          this.invoiceTitle = '同意开票申请'
          this.invoiceForm.id = row.id
        }, // 通过
        handleCancel () {
          this.invoiceForm = {}
          this.invoiceShow = true
          this.invoiceTitle = '取消开票申请'
        }, // 取消
        handleRejeict (row) {
          this.invoiceForm = {}
          this.invoiceShow = true
          this.invoiceTitle = '驳回开票申请'
          this.invoiceForm.id = row.id
        }, // 驳回
        toContractDetail (id, name) {
          this.currentId = id
          id = String(name)
          const flag = this.tabs.some(value => {
            return name === value.name
          })
          if (!flag) {
            this.tabs.push({ id, name })
          }
          this.currentTab = id
        }, // 重复标签
        /**
             * 移除tab
             */
        removeTab (name) {
          const pos = this.removeTabDetial(this.tabs, name)
          if (pos) {
            return
          }
          this.removeTabDetial(this.leaseIds, name)
        },

        /**
             * 删除tab具体过程
             * @param {Array} obj
             * @param {String} tabName 关闭的列表名
             * @return {Boolean} true => 表示找到已经删除的tab false => 表示循环完之后依旧没有找到要关闭的tab
             */
        removeTabDetial (arr, tabName) {
          // let { length } = arr;
          for (let i = 0; i < arr.length; i++) {
            const { id } = arr[i]
            if (id === tabName) {
              arr.splice(i, 1)
              return true
            }
          }
          return false
        },
        remoteMethodMangersign (query) {
          if (!this.formValidate.clientId) {
            this.$Message.error('请选择签约商户')
          } else {
            this.mangersignLoading = true
            this.getMangersign(query)
          }
        }, // 客户签约主体select
        async getMangersign (id) {
          let res = (await http.fetch(this, api.client_finance_info, null, null)).contract_body
          this.mangersignLoading = false
          this.mangersign = res.map(item => {
            return {
              value: item.id,
              label: item.company_name
            }
          })
        }, // 客户签约主体
        handleAudit (name) {
          this.invoiceForm.updateBy = 0
          this.$refs[name].validate((valid) => {
            if (!valid) {
              this.$message('备注不能为空')
            } else {
              if (this.invoiceTitle === '驳回开票申请') {
                http.request(this, api.invoice_reject, null, this.invoiceForm, (res, err) => {
                  if (!res) return
                  this.$message('驳回开票申请')
                  this.invoiceShow = false
                  this.invoiceForm = {}
                  this.getClientList(1)
                })
              } else if (this.invoiceTitle === '取消开票申请') {
                http.request(this, api.invoice_cancel, null, this.invoiceForm, (res, err) => {
                  if (!res) return
                  this.$message('取消开票申请')
                  this.invoiceShow = false
                  this.invoiceForm = {}
                  this.getClientList(1)
                })
              } else {
                http.request(this, api.invoice_confirm, null, this.invoiceForm, (res, err) => {
                  if (!res) return
                  this.$message('通过开票申请')
                  this.invoiceShow = false
                  this.invoiceForm = {}
                  this.getClientList(1)
                })
              }
            }
          })
        }, // 通过驳回
        handleInvoiceCancel () {
          this.invoiceShow = false
          this.$refs['invoiceForm'].resetFields()
        },
        async getUserInfo (id) {
          let res = await http.fetch(this, api.user_info, null, null)
          this.roleId = res.role_id
          this.client = {
            clientId: res.client_id,
            clientName: res.client.name
          }
          this.getClientList(1)
          sessionStorage.setItem('user', JSON.stringify(res))
        }, // 用户信息
        createStartTimeChange (val, date) {
          if (!val) return
          this.filterData.createStartTime = moment(this.filterData.createStartTime).format('YYYY-MM-DD HH:mm:ss')
        }, // 开始时间
        createEndTimeChange (val, date) {
          if (!val) return
          this.filterData.createEndTime = moment(this.filterData.createEndTime).format('YYYY-MM-DD HH:mm:ss')
        }, // 结束时间
        callback (val) {
          console.log(val)
        }// 账单申请开票
      }
    }
</script>
<style lang="less" scoped>
  .flex-style {
    & > .ivu-col {
        display: flex;
        align-items: center;
        .flex-items {
            flex: 1;
            margin-left: 5px;
        }
    }
}
</style>

